package com.studyweb;

import com.studyweb.utils.AliyunOssProperties;
import com.studyweb.utils.FileUploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Study Web 主应用启动类
 * 
 * <p>这是整个Study Web应用的入口点，负责：</p>
 * <ul>
 *   <li>启动Spring Boot应用</li>
 *   <li>配置MyBatis Mapper扫描</li>
 *   <li>测试数据库连接</li>
 *   <li>初始化应用环境</li>
 * </ul>
 * 
 * @author StudyWeb Team
 * @since 1.0.0
 */
@Slf4j
@SpringBootApplication
@ComponentScan("com.studyweb")
@MapperScan("com.studyweb.mapper")
@EnableConfigurationProperties({FileUploadProperties.class, AliyunOssProperties.class})
public class StudyWebApplication implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    /**
     * 应用程序主入口方法
     * 
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        log.info("=== Study Web Application Starting ===");
        SpringApplication.run(StudyWebApplication.class, args);
        log.info("=== Study Web Application Started Successfully ===");
    }

    /**
     * 应用启动后执行的方法
     * 
     * @param args 命令行参数
     * @throws Exception 执行过程中可能出现的异常
     */
    @Override
    public void run(String... args) throws Exception {
        testDatabaseConnection();
    }

    /**
     * 测试数据库连接并输出连接信息
     * 
     * <p>该方法会在应用启动后自动执行，用于验证数据库连接是否正常，
     * 并输出数据库的详细信息，包括数据库类型、版本、连接地址等。</p>
     * 
     * @throws SQLException 数据库连接异常时抛出
     */
    private void testDatabaseConnection() {
        try (Connection connection = dataSource.getConnection()) {
            String url = connection.getMetaData().getURL();
            String username = connection.getMetaData().getUserName();
            String databaseProductName = connection.getMetaData().getDatabaseProductName();
            String databaseProductVersion = connection.getMetaData().getDatabaseProductVersion();
            
            log.info("=== 数据库连接测试成功 ===");
            log.info("数据库类型: {}", databaseProductName);
            log.info("数据库版本: {}", databaseProductVersion);
            log.info("连接地址: {}", url);
            log.info("用户名: {}", username);
            log.info("连接状态: 正常");
            log.info("=== 数据库连接验证完成 ===");
        } catch (SQLException e) {
            log.error("=== 数据库连接失败 ===");
            log.error("错误信息: {}", e.getMessage());
            log.error("请检查数据库配置和网络连接");
        }
    }
}